﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PlanningGIS.Framework.Config;
using PlanningGIS.ManageUtility;
using PlanningGIS.Win.Controls;
using PlanningGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using PlanningGIS.ArcGIS;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
using System.Collections;
using ESRI.ArcGIS.Geometry;
using DevComponents.AdvTree;
using ESRI.ArcGIS.Controls;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 范围权限
    /// </summary>
    public partial class CtlRegion : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlRegion()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 选择的节点的值
        /// </summary>
        private string _CheckedValuesTemp = "";

        /// <summary>
        /// 选择的节点的值
        /// </summary>
        private string _CheckedValues = "";

        /// <summary>
        /// 获取或设置选择的节点的值
        /// </summary>
        public string CheckedValues
        {
            get
            {
                _CheckedValuesTemp = "";
                GetCheckValue(advTree.Nodes);
                if (_CheckedValuesTemp.EndsWith(","))
                    _CheckedValuesTemp = _CheckedValuesTemp.Substring(0, _CheckedValuesTemp.Length - 1);
                //_CheckedValues = _CheckedValuesTemp;
                return _CheckedValuesTemp;
            }
            set
            {
                _CheckedValues = value;
                _CheckedValuesTemp = value;
                SetCheckValue(advTree.Nodes, value);
            }
        }

        /// <summary>
        /// 获取选择对象是否发生改变
        /// </summary>
        public bool IsChange
        {
            get
            {
                _CheckedValuesTemp = "";
                GetCheckValue(advTree.Nodes);
                if (_CheckedValuesTemp.EndsWith(","))
                    _CheckedValuesTemp = _CheckedValuesTemp.Substring(0, _CheckedValuesTemp.Length - 1);
                if (_CheckedValues.Equals(_CheckedValuesTemp)) return false;
                return true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void ResetControl()
        {
            _CheckedValues = CheckedValues;
        }
        /// <summary>
        /// 
        /// </summary>
        private IFeatureLayer _FeatLyr = null;
        /// <summary>
        /// 加载窗体
        /// </summary>
        public void LoadControl()
        {
            try
            {
                if (ManageHelper.PrivilegeCfg == null
                    || string.IsNullOrWhiteSpace(ManageHelper.PrivilegeCfg.RegionFieldName)
                    || string.IsNullOrWhiteSpace(ManageHelper.PrivilegeCfg.RegionLayerName))
                {
                    MsgHelper.ShowErrorMsgbox("权限配置有误，请联系管理员修改权限配置！");
                    return;
                }
                IWorkspace w = PlanningGIS.ArcGIS.WorkspaceHelper.OpenGDBWorkspace(AppConfig.DataFullName);
                if (w == null) return;
                IFeatureClass fcls = GeodatabaseHelper.OpenFeatureClass(w, ManageHelper.PrivilegeCfg.RegionLayerName);
                if (fcls == null)
                {
                    MsgHelper.ShowErrorMsgbox("范围图层配置有误");
                    return;
                }
                ArrayList arr = FieldHelper.GetUniqueValuesByQueryDef(fcls, ManageHelper.PrivilegeCfg.RegionFieldName);
                if (arr == null || arr.Count == 0) return;

                IFeatureRenderer render = RendererHelper.CreateUniqueValueRenderer(ManageHelper.PrivilegeCfg.RegionFieldName, arr,
                    new RgbColor() { Red = 152, Green = 164, Blue = 181 },
                    new RgbColor() { Red = 191, Green = 227, Blue = 198 });
                _FeatLyr = new FeatureLayer();
                _FeatLyr.FeatureClass = fcls;
                ((IGeoFeatureLayer)_FeatLyr).Renderer = render;
                axMapControl1.AddLayer(_FeatLyr);
                axMapControl1.Extent = _FeatLyr.AreaOfInterest;
                //IPoint pt = new ESRI.ArcGIS.Geometry.Point() as IPoint;
                //pt.X = (lyr.AreaOfInterest.XMin + lyr.AreaOfInterest.XMax) / 2;
                //pt.Y = (lyr.AreaOfInterest.YMin + lyr.AreaOfInterest.YMax) / 2;
                //axMapControl1.CenterAt(pt);
                foreach (object v in arr)
                {
                    Node nd = new Node();
                    nd.Text = v.ToString();
                    nd.CheckBoxVisible = true;
                    nd.Checked = false;
                    nd.DragDropEnabled = false;
                    advTree.Nodes.Add(nd);
                }

                IGeoFeatureLayer pGeoFeatureLayer = _FeatLyr as IGeoFeatureLayer;
                pGeoFeatureLayer.AnnotationProperties.Clear();//必须执行，因为里面有一个默认的
                IBasicOverposterLayerProperties pBasic = new BasicOverposterLayerProperties();
                ILabelEngineLayerProperties pLableEngine = new LabelEngineLayerProperties() as ILabelEngineLayerProperties;
                ITextSymbol pTextSymbol = new TextSymbol();
                //pTextSymbol.
                //你可以在这里修改样式的颜色和字体等属性，本文从略
                //pTextSymbol.Color = new RgbColor(){RGB =System.Drawing.ColorTranslator.ToOle(Color.Black)};
                //pTextSymbol.Font 
                string pLable = "[" + ManageHelper.PrivilegeCfg.RegionFieldName + "]";
                pLableEngine.Expression = pLable;
                pLableEngine.IsExpressionSimple = true;
                pBasic.NumLabelsOption = esriBasicNumLabelsOption.esriOneLabelPerShape;
                pLableEngine.BasicOverposterLayerProperties = pBasic;
                pLableEngine.Symbol = pTextSymbol;
                pGeoFeatureLayer.AnnotationProperties.Add(pLableEngine as IAnnotateLayerProperties);
                pGeoFeatureLayer.DisplayAnnotation = true;
                axMapControl1.Refresh();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
        }

        /// <summary>
        /// 设置当前选择的区域名称
        /// </summary>
        /// <param name="nodes">要设置的节点</param>
        /// <param name="names">已选择的名称</param>
        private void SetCheckValue(NodeCollection nodes, string names)
        {
            foreach (Node nd in nodes)
            {
                if (nd.Nodes.Count > 0)
                    SetCheckValue(nd.Nodes, names);
                if (string.IsNullOrWhiteSpace(names))
                {
                    nd.Checked = false;
                }
                else
                {
                    string[] ns = names.Split(',');
                    if (ns.Contains(nd.Text)) nd.Checked = true;
                    else nd.Checked = false;
                }
            }
        }

        /// <summary>
        /// 获取选择的区域名称
        /// </summary>
        /// <param name="nodes"></param>
        private void GetCheckValue(NodeCollection nodes)
        {
            if (nodes == null || nodes.Count == 0) return;
            foreach (Node nd in nodes)
            {
                if(nd.Checked)
                    _CheckedValuesTemp += nd.Text + ",";
                GetCheckValue(nd.Nodes);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enable"></param>
        public void SetEnableAll(bool enable)
        {
            SetEnableAll(enable, advTree.Nodes);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="enable"></param>
        /// <param name="nodes"></param>
        public void SetEnableAll(bool enable, NodeCollection nodes)
        {
            if (nodes == null || nodes.Count == 0) return;
            foreach (Node nd in nodes)
            {
                SetEnableAll(enable, nd.Nodes);
                nd.Checked = enable;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void advTree_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            if (_FeatLyr == null) return;
            string name = e.Node.Text.Trim();
            if (string.IsNullOrWhiteSpace(name)) return;
            ISpatialFilter flt = new SpatialFilter();
            flt.WhereClause = ManageHelper.PrivilegeCfg.RegionFieldName + " = '" + name + "'";

            IFeatureCursor cur = _FeatLyr.Search(flt, false);
            IFeature f = cur.NextFeature();
            if (f != null)
            {
                FlashHelper.FlashFeature(f, (IMapControl3)axMapControl1.Object);
            }
        }
    }
}
